import React, { useState } from 'react';

import {
  Button,
  Card,
  Grid,
  Image,
  message,
  Upload,
} from 'antd';

import { PlusOutlined } from '@ant-design/icons';

import { useAuthenticatedFetch } from '../hooks';

const { useBreakpoint } = Grid;

const PhotoWall = (props) => {

  const fetch = useAuthenticatedFetch();

  // 定义上传图片
  const [uploadedPhotos, setUploadedPhotos] = useState([]);

  // 处理上传图片
  const handleUpload =(file) => {
    const reader = new FileReader();
    reader.onload =async (e) => {
      const id = Date.now();
      const src = e.target.result;
      // setUploadedPhotos([...uploadedPhotos, { id, src }]);
      try {
        const {
          data
        } = await fetch( "/api/products/create_image",{
          method:"POST",
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            attachment: src.replace(`data:image/${file.name.split('.')[1]};base64,`,''),
            suffix:file.name.split('.')[1],
            product_id:props.product.key
          })
        });
        message.success('success!')
      } catch (error) {
        console.log(error,'error')
        message.error('error!')

      }

    };
    reader.readAsDataURL(file);
  };

  // 上传组件
  const UploadComponent = () => (
    <Upload
      name="photo"
      accept="image/*"
      showUploadList={false}
      beforeUpload={(file) => {
        handleUpload(file);
        return false;
      }}
    >
      <Card hoverable style={{ width: '100%', height: 200, display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
        <PlusOutlined style={{ fontSize: 32 }} />
      </Card>
    </Upload>
  );

  // 获取屏幕大小
  const screens = useBreakpoint();

  return (
    <div style={{ padding: 24 }}>
     
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 24 }}>
        {/* 显示静态图片 */}
        {props.product.images.map((photo) => (
          <Card key={photo.id} hoverable style={{ width: screens.xxl ? '20%' : '25%' }}>
            <Image src={photo.src} alt="photo" width="100%" />
            <Button onClick={()=> {props.onClick(photo)}}>Edit</Button>
          </Card>
        ))}

        {/* 显示上传图片 */}
        {uploadedPhotos.map((photo) => (
          <Card key={photo.id} hoverable style={{ width: screens.xxl ? '20%' : '25%' }}>
            <Image src={photo.src} alt="photo" width="100%" />
          </Card>
        ))}

        {/* 上传图片 */}
        {screens.xxl || screens.xl ? (
          <Card style={{ width: '20%' }}>
            <UploadComponent />
          </Card>
        ) : (
          <UploadComponent />
        )}
      </div>
    </div>
  );
};

export default PhotoWall;
